<?php
namespace Modules\User\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\User\Entities\User;

use Validator;
use ThrowException;
use DB;

class VipUserController extends Controller
{
    // VIP会员列表
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['with'] = ['inviter'];
        $options['with_count'] = ['invitees'];

        if ($req->input('sort')) {
            if ($req->sort === 'invitee')
                $options['order_by'] = ['invitees_count' => 'desc'];
        }

        $options['scopes'] = ['vip'];

        $options['only'] = [
            'id',
            'uuid',
            'name',
            'real_name',
            'number',
            'card_number',
            'phone',
            'gender',
            'headimg',
            'email',
            'birthday',
            'city',
            'area',
            'score',
            'redpack',
            'level_text',
            'client_type',
            'vip_start_at',
            'vip_end_at',
            'status',
            'invitees_count',
            'last_active_at',
            'created_at',
            'inviter' => [
                'id',
                'uuid',
                'name',
                'headimg'
            ]
        ];

        $list = User::getList($options);

        $list->each(function ($item) {
            $item->score = $item->asset('score')->balance;
            $item->redpack = $item->asset('redpack')->balance;
        });

        return $list->generateListResponse();
    }

    // 单个VIP会员详情
    public function show(Request $req, $uuid)
    {
        $item = User::getEntity([
            'uuid' => $uuid,
            'with' => [
                'ext',
                'skus'
            ]
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    // 更新VIP会员信息
    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = User::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);
        }

        DB::commit();

        return [];
    }

    // 删除用户
    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = User::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
